package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.anno.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    @GuiGuLogin
    @PostMapping(value = "/createJsapi/{paymentType}/{orderNo}")
    public Result<WeChatPayVo> createJsapi(@PathVariable(value = "paymentType") String paymentType ,
                                           @PathVariable(value = "orderNo") String orderNo) {
        WeChatPayVo weChatPayVo = wxPayService.createJsapi(paymentType , orderNo) ;
        return Result.build(weChatPayVo , ResultCodeEnum.SUCCESS) ;
    }

    @GetMapping(value = "/queryPayStatus/{orderNo}")
    public Result<Boolean> queryPayStatus(@PathVariable(value = "orderNo") String orderNo) {
        Boolean flag = wxPayService.queryPayStatus(orderNo) ;
        return Result.build(flag , ResultCodeEnum.SUCCESS) ;
    }

    /**
     * ResponseEntity是由spring框架所提供的一个对象，该对象是用来封装http的状态码和响应数据
     */
    @PostMapping(value = "/notify")
    public ResponseEntity<Map<String , String>> notify(HttpServletRequest request) {
        log.info("WxPayApiController...notify方法执行了...");
        Map<String , String> map = new HashMap<>() ;
        try {
            wxPayService.asyncNotify(request) ;
            map.put("code" , "SUCCESS") ;
            map.put("message" , "成功") ;
            return ResponseEntity.status(HttpStatus.OK).body(map) ;
        }catch (Exception e) {
            e.printStackTrace();
            map.put("code" , "FAIL") ;
            map.put("message" , "失败") ;
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map) ;
        }
    }

}
